package com.qfedu.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;

@WebServlet
public class BaseServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String method = request.getParameter("method");
        Class<? extends BaseServlet> clazz = this.getClass();
        try {
            Method methodName = clazz.getMethod(method, HttpServletRequest.class, HttpServletResponse.class);
            Object invoke = methodName.invoke(clazz.newInstance(), request, response);
            if (invoke instanceof String) {
                String resultStr = (String) invoke;
                if (resultStr.contains("forward:")){
                    String substring = resultStr.substring(resultStr.indexOf(":")+1);
                    System.out.println(substring);
                    request.getRequestDispatcher(request.getContextPath()+substring).forward(request,response);
                }
                if (resultStr.contains("direct:")){
                    String substring = resultStr.substring(resultStr.indexOf(":")+1);
                    response.sendRedirect(request.getContextPath()+substring);
                }
            }else {
                response.setContentType("application/json;charset=utf-8");
                ObjectMapper objectMapper = new ObjectMapper();
                String string = objectMapper.writeValueAsString(invoke);
                PrintWriter writer = response.getWriter();
                writer.print(string);
                writer.flush();
                writer.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.sendRedirect("error/error.jsp");
        }
    }
}
